<script lang="ts" setup>
import { loanStats } from '@/api/lending'

defineOptions({
  name: 'HomeContent',
})

// API返回数据类型定义
interface LoanStatsResponse {
  apply_cnt: number // 申请数量
  audit_approved_count: number // 审核通过数量
  avg_apr: number // 平均年化利率
  avg_audit_days: number // 平均审核天数
  due_amount: number // 逾期金额
  due_rate: number // 逾期率
  has_repayment_amount: number // 已回款金额
  left_interest: number // 剩余利息
  left_principal: number // 剩余本金
  pending_loan1: number // 待审放款1
  pending_loan2: number // 待审放款2
  progress: number // 进度
  released_loan: number // 已放款金额
  schedule_ids: number // 计划ID数量
  total_pending_loan: number // 总待放款
  user_cnt: number // 用户数量
}

// 响应式数据
const apiData = ref<LoanStatsResponse>({
  apply_cnt: 0,
  audit_approved_count: 0,
  avg_apr: 0,
  avg_audit_days: 0,
  due_amount: 0,
  due_rate: 0,
  has_repayment_amount: 0,
  left_interest: 0,
  left_principal: 0,
  pending_loan1: 0,
  pending_loan2: 0,
  progress: 0,
  released_loan: 0,
  schedule_ids: 0,
  total_pending_loan: 0,
  user_cnt: 0,
})

// 计算属性 - 资金池总额（可以根据业务逻辑调整计算方式）
const totalFund = computed(() => {
  return apiData.value.released_loan + apiData.value.has_repayment_amount + apiData.value.left_principal
})

// 获取统计数据
async function getLoanStats() {
  try {
    const res = await loanStats()
    // 将API返回的数据赋值给响应式数据
    apiData.value = res as any
  }
  catch (error) {
    console.error('获取统计数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    })
  }
}

// 暴露activated方法给父组件调用
function actived() {
  getLoanStats()
}
// 暴露方法给父组件
defineExpose({
  actived,
})
// 获取屏幕边界到安全区域距离
let safeAreaInsets
let systemInfo

// #ifdef MP-WEIXIN
// 微信小程序使用新的API
systemInfo = uni.getWindowInfo()
safeAreaInsets = systemInfo.safeArea
  ? {
    top: systemInfo.safeArea.top,
    right: systemInfo.windowWidth - systemInfo.safeArea.right,
    bottom: systemInfo.windowHeight - systemInfo.safeArea.bottom,
    left: systemInfo.safeArea.left,
  }
  : null
// #endif

// #ifndef MP-WEIXIN
// 其他平台继续使用uni API
systemInfo = uni.getSystemInfoSync()
safeAreaInsets = systemInfo.safeAreaInsets
// #endif
// 格式化金额显示
function formatAmount(amount: number) {
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 1,
    maximumFractionDigits: 2,
  })
}

// 查看更多操作
function viewMore(type: string) {
  console.log(`查看更多: ${type}`)
  // 这里可以跳转到对应的详情页面
  uni.navigateTo({
    url: `/pages-sub/financial/repayment`,
  })
}

console.log('HomeContent component loaded')
</script>

<template>
  <view class="bg-gray-50">
    <!-- 资金池卡片 -->
    <view class="mx-4 mb-2 mt-4">
      <view class="relative overflow-hidden rounded-2xl from-orange-400 to-yellow-400 bg-gradient-to-r p-6 text-white">
        <view class="absolute right-0 top-0 h-20 w-20 rounded-full bg-white bg-opacity-10 -mr-10 -mt-10" />
        <view class="flex items-center justify-between">
          <view class="flex items-center">
            <text class="text-lg font-medium">已放款 💰</text>
          </view>
        </view>
        <view class="mb-2">
          <text class="text-3xl font-bold">{{ formatAmount(apiData.released_loan) }}</text>
        </view>
        <view class="text-sm opacity-80">
          <text>请在放款前请仔细核实风险评估</text>
        </view>
      </view>
    </view>

    <!-- 问候语 -->
    <view class="mx-4 mb-2">
      <text class="text-lg text-gray-800 font-bold">您好，欢迎使用</text>
    </view>

    <!-- 数据卡片网格 -->
    <view class="grid grid-cols-2 mx-4 gap-4">
      <!-- 已放款 -->
      <view class="rounded-2xl bg-white p-4 shadow-sm">
        <view class="mb-2 flex items-center justify-between">
          <view class="h-8 w-8 center rounded-lg bg-green-100">
            <text class="text-lg text-green-600">📊</text>
          </view>
          <text class="text-30rpx text-green-600 font-medium">已放款</text>
        </view>

        <view class="mb-2">
          <text class="text-2xl text-green-800 font-bold">{{ formatAmount(apiData.released_loan) }}</text>
        </view>

        <view class="mb-2 text-28rpx text-gray-500 space-y-1">
          <view class="flex justify-between">
            <text>申请配资：</text>
            <text>{{ apiData.apply_cnt }} 笔</text>
          </view>
          <view class="flex justify-between">
            <text>审核通过：</text>
            <text>{{ apiData.audit_approved_count }} 笔</text>
          </view>
          <view class="flex justify-between">
            <text>平均年化：</text>
            <text>{{ apiData.avg_apr }}%</text>
          </view>
        </view>

        <view class="flex items-center text-28rpx text-blue-600" @tap="viewMore('loan')">
          <text class="mr-1">查看更多</text>
          <uni-icons type="right" color="blue-600" size="12" />
        </view>
      </view>

      <!-- 已回款 -->
      <view class="rounded-2xl bg-white p-4 shadow-sm">
        <view class="mb-2 flex items-center justify-between">
          <view class="h-8 w-8 center rounded-lg bg-blue-100">
            <text class="text-lg text-blue-600">💰</text>
          </view>
          <text class="text-30rpx text-blue-600 font-medium">已回款</text>
        </view>

        <view class="mb-2">
          <text class="text-2xl text-blue-800 font-bold">{{ formatAmount(apiData.has_repayment_amount) }}</text>
        </view>

        <view class="mb-2 text-28rpx text-gray-500 space-y-1">
          <view class="flex justify-between">
            <text>剩余本金：</text>
            <text>{{ formatAmount(apiData.left_principal) }}</text>
          </view>
          <view class="flex justify-between">
            <text>待收利息：</text>
            <text>{{ formatAmount(apiData.left_interest) }}</text>
          </view>
          <view class="flex justify-between">
            <text>回款比例：</text>
            <text>{{ (apiData.progress * 100).toFixed(1) }}%</text>
          </view>
        </view>

        <view class="flex items-center text-28rpx text-blue-600" @tap="viewMore('repayment')">
          <text class="mr-1">查看更多</text>
          <uni-icons type="right" color="blue-600" size="12" />
        </view>
      </view>

      <!-- 逾期款 -->
      <view class="rounded-2xl bg-white p-4 shadow-sm">
        <view class="mb-2 flex items-center justify-between">
          <view class="h-8 w-8 center rounded-lg bg-red-100">
            <text class="text-lg text-red-600">⚠️</text>
          </view>
          <text class="text-30rpx text-red-600 font-medium">逾期款</text>
        </view>

        <view class="mb-2">
          <text class="text-2xl text-red-800 font-bold">{{ formatAmount(apiData.due_amount) }}</text>
        </view>

        <view class="mb-2 text-28rpx text-gray-500 space-y-1">
          <view class="flex justify-between">
            <text>逾期配资：</text>
            <text>{{ apiData.schedule_ids }} 笔</text>
          </view>
          <view class="flex justify-between">
            <text>逾期人数：</text>
            <text>{{ apiData.user_cnt }} 个</text>
          </view>
          <view class="flex justify-between">
            <text>逾期率：</text>
            <text>{{ (apiData.due_rate * 100).toFixed(2) }}%</text>
          </view>
        </view>

        <view class="flex items-center text-28rpx text-blue-600" @tap="viewMore('overdue')">
          <text class="mr-1">查看更多</text>
          <uni-icons type="right" color="blue-600" size="12" />
        </view>
      </view>

      <!-- 待放款 -->
      <view class="rounded-2xl bg-white p-4 shadow-sm">
        <view class="mb-2 flex items-center justify-between">
          <view class="h-8 w-8 center rounded-lg bg-purple-100">
            <text class="text-lg text-purple-600">🎯</text>
          </view>
          <text class="text-30rpx text-purple-600 font-medium">待放款</text>
        </view>

        <view class="mb-2">
          <text class="text-2xl text-purple-800 font-bold">{{ formatAmount(apiData.total_pending_loan) }}</text>
        </view>

        <view class="mb-2 text-28rpx text-gray-500 space-y-1">
          <view class="flex justify-between">
            <text>待审放款：</text>
            <text>{{ formatAmount(apiData.pending_loan1) }}</text>
          </view>
          <view class="flex justify-between">
            <text>待支放款：</text>
            <text>{{ formatAmount(apiData.pending_loan2) }}</text>
          </view>
          <view class="flex justify-between">
            <text>审核时效：</text>
            <text>{{ apiData.avg_audit_days }} 天</text>
          </view>
        </view>

        <view class="flex items-center justify-between">
          <view class="flex items-center text-28rpx text-blue-600" @tap="viewMore('pending')">
            <text class="mr-1">查看更多</text>
            <uni-icons type="right" color="blue-600" size="12" />
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.grid {
  display: grid;
}

.grid-cols-2 {
  grid-template-columns: repeat(2, 1fr);
}

.gap-4 {
  gap: 1rem;
}

/* 修复：将通用选择器 * 替换为具体的 view 选择器 */
.space-y-1>view+view {
  margin-top: 0.25rem;
}

.bg-gradient-to-r {
  background: linear-gradient(to right, var(--tw-gradient-stops));
}

.from-orange-400 {
  --tw-gradient-from: #fb923c;
  --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to, rgba(251, 146, 60, 0));
}

.to-yellow-400 {
  --tw-gradient-to: #facc15;
}

.justify-between {
  &>text:first-child {
    width: max-content;
  }
}
</style>
